<?php

class PersonController extends AppController {

	var $paginate = array(
		'Person' => array('order' => 'Person.id DESC', 'limit' => 10),
	);
	
	public function index() {
		$personTypes = $this->PersonType->find("all");
		$this->set('personTypes', $personTypes);

		$conditions = array();
		if ($this->request->params['pass']) {
			$parameters = $this->request->params['pass'];

			if (isset($parameters[0])) {
				$type = trim(addslashes($parameters[0]));
				$this->set('actualType', $type);
				foreach ($personTypes as $personType) {
					if ($personType['PersonType']['title'] == $type) {
						$conditions['Person.fk_person_type_id'] = $personType['PersonType']['id'];
					}
				}
			}
		}
		$this->Person->recursive = 0;
		$this->set('persons', $this->paginate($conditions));
	}

	public function view($id = null) {
		$this->Person->id = $id;
		if (!$this->Person->exists()) {
			$this->setFlashError('Záznam nebol nájdený.');
			$this->redirect(array('action' => 'index'));
		}
		
		$showDetailData = TRUE;
		$actualUser = $this->Session->read('Auth.User');
		if (in_array($actualUser['Person']['fk_person_type_id'], array(PersonType::PT_BROKER))) {
			$showDetailData = FALSE;
		} elseif (in_array($actualUser['Person']['fk_person_type_id'], array(PersonType::PT_F3, PersonType::PT_T1, PersonType::PT_T2, PersonType::PT_T3))) {
			$showDetailData = FALSE;
		}
		
		$this->set('showDetailData', $showDetailData);
		$this->set('person', $this->Person->read(null, $id));
		
		$marketConditions = array(
			'or' => array(
				array('Market.fk_client_id' => $id),
				array('Market.fk_tipster_id' => $id),
				array('Market.fk_broker_id' => $id),
			)
		);
		
		$this->set('offers', $this->Market->find('all', array('order' => 'Market.id DESC', 'conditions' => array_merge(array('Market.type' => Market::MT_OFFER), $marketConditions))));
		$this->set('demands', $this->Market->find('all', array('order' => 'Market.id DESC', 'conditions' => array_merge(array('Market.type' => Market::MT_DEMAND), $marketConditions))));

		$conditions = array(
			'Commission.fk_person_id' => $id,
		);
		$this->set('commissions', $this->Commission->find('all', array('order' => 'Commission.id DESC', 'conditions' => $conditions)));
	}

	public function add() {
		if ($this->request->is('post')) {
			$this->Person->create();
			if ($this->createPersonBirthDate()) {
				
				// parenta nechame len tym typom ktore mozu mat parenta				
				if (!in_array($this->request->data['Person']['fk_person_type_id'], array(5, 6, 7))) {
					$this->request->data['Person']['fk_parent_person_id'] = 0;
				}
				
				if (isset($this->request->data['create_user_button']) && $this->request->data['create_user_button'] == 1) {
					$name = $this->request->data['Person']['name'];
					$surname = $this->request->data['Person']['surname'];
					
					$slugName = Inflector::slug($name, '.');
					$slugSurname = Inflector::slug($surname, '.');
					
					$this->request->data['User']['username'] = strtolower($slugName . '.' . $slugSurname);
					$this->request->data['User']['password'] = strtolower($slugSurname) . '123';
					$this->set('createUser', TRUE);
				} else {
					if (isset($this->request->data['Person']['create_user']) && $this->request->data['Person']['create_user'] == 1) {
						$this->set('createUser', TRUE);
					}
					if ($this->Person->save($this->request->data)) {
						$this->request->data['User']['fk_person_id'] = $this->Person->id;
						
						if (isset($this->request->data['Person']['create_user']) && $this->request->data['Person']['create_user'] == 1) {
							if ($this->User->save($this->request->data['User'])) {
								$message = '<p>Dobrý deň,</p>';
								$message .= '<p>v systéme MNH group (<a href="http://www.mnh.sk">mnh.sk</a>) Vám bolo vytvorené konto.</p>';
								$message .= '<p>Používateľské meno: ' . $this->request->data['User']['username'] . '</p>';
								$message .= '<p>Heslo: ' . $this->request->data['User']['password'] . '</p>';
								$message .= '<p>Prajeme Vám pekný deň.</p>';
								$this->sendMail($this->request->data['Person']['email'], 'Nové konto v systéme mnh.sk', $message);
							}
						}
						$this->setFlashSuccess('Záznam bol uložený do databázy.');
						$this->redirect(array('action' => 'index'));
					} else {
						$this->setFlashError('Záznam sa nepodarilo uložiť do databázy.');
					}
				}
			}
		}
		$personList = $this->getParentList();
		$this->set('personList', $personList);
		
		$personTypeList = $this->getPersonTypeList();
		$this->set('personTypeList', $personTypeList);
	}

	protected function getParentList() {
		$conditions = array('Person.fk_person_type_id' => array(PersonType::PT_ADMIN, PersonType::PT_T3, PersonType::PT_T2, PersonType::PT_T1));
		return $this->Person->find("all", array('conditions' => $conditions, 'order' => 'Person.full_name'));
	}
	
	protected function getPersonTypeList() {
		$conditions = array('PersonType.id NOT' => PersonType::PT_COMPANY);
		return $this->PersonType->find("all", array('conditions' => $conditions, 'order' => 'PersonType.title'));
	}
	
	public function edit($id = null) {
		$this->Person->id = $id;
		if (!$this->Person->exists()) {
			$this->setFlashError('Záznam nebol nájdený.');
			$this->redirect(array('action' => 'index'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			if ($this->createPersonBirthDate()) {
				
				// parenta nechame len tym typom ktore mozu mat parenta				
				if (!in_array($this->request->data['Person']['fk_person_type_id'], array(5, 6, 7))) {
					$this->request->data['Person']['fk_parent_person_id'] = 0;
				}
				
				if ($this->Person->save($this->request->data)) {
					$this->setFlashSuccess('Záznam bol uložený do databázy.');
					$this->redirect(array('action' => 'index'));
				} else {
					$this->setFlashError('Záznam sa nepodarilo uložiť do databázy.');
				}
			}
		} else {
			$this->request->data = $this->Person->read(null, $id);
			$this->request->data['Person']['birthday_select']['day'] = $this->request->data['Person']['birth_day'];
			$this->request->data['Person']['birthday_select']['month'] = $this->request->data['Person']['birth_month'];
			$this->request->data['Person']['birthday_select']['year'] = $this->request->data['Person']['birth_year'];
		}
		$personList = $this->getParentList();
		$this->set('personList', $personList);

		$personTypeList = $this->getPersonTypeList();
		$this->set('personTypeList', $personTypeList);
	}

	protected function createPersonBirthDate() {
		$birthDateNotAvailable = $this->request->data['Person']['birthdate_not_available'];
		if ($birthDateNotAvailable) {
			$this->request->data['Person']['birth_day'] = 0;
			$this->request->data['Person']['birth_month'] = 0;
			$this->request->data['Person']['birth_year'] = 0;
			return TRUE;
		} else {
			$day = intval($this->request->data['Person']['birthday_select']['day']);
			$month = intval($this->request->data['Person']['birthday_select']['month']);
			$year = intval($this->request->data['Person']['birthday_select']['year']);
			
			if (checkdate($month, $day, $year)) {
				$this->request->data['Person']['birth_day'] = $day;
				$this->request->data['Person']['birth_month'] = $month;
				$this->request->data['Person']['birth_year'] = $year;
				return TRUE;
			} else {
				$this->setFlashError('Zadali ste neexistujúci dátum. Záznam sa nepodarilo uložiť do databázy.');
				return FALSE;
			}
		}
	}

	public function delete($id = null) {
		$this->Person->id = $id;
		if (!$this->Person->exists()) {
			$this->setFlashError('Záznam nebol nájdený.');
		} else {
			if ($this->Person->delete()) {
				$this->setFlashSuccess('Záznam bol zmazaný z databázy.');
			} else {
				$errors = array_merge(array('Záznam nebol zmazaný z databázy.'), Errors::getErrors());
				$message = implode("<br />", $errors);
				$this->setFlashError($message);
			}
		}
		$this->redirect(array('action' => 'index'));
	}

	public function tree() {
		$actualUser = $this->Session->read('Auth.User');
		if (in_array($actualUser['Person']['fk_person_type_id'], PersonType::getTipsterTypeList())) {
			$conditions = array('Person.id' => $actualUser['Person']['id']);
		} else {
			// vyberieme person types, ktore su top of the structure
			$personTypes = $this->PersonType->find('list', array('fields' => array('PersonType.id'), 'conditions'=> array('PersonType.top_of_structure' => 1)));
			$conditions = array('Person.fk_person_type_id' => $personTypes);
		}
		
		// vyber osob ktore patria k top person typom
		$this->Person->recursive = 0;
		$persons = $this->Person->find('all', array('conditions' => $conditions));
		$this->set('persons', $persons);
	}
}

?>